<template>
  <el-breadcrumb separator-class="ArrayRight">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>订单管理</el-breadcrumb-item>
    <el-breadcrumb-item>创建订单</el-breadcrumb-item>
  </el-breadcrumb>  
  <el-card>
    <!-- 订单主表信息录入布局 -->
    <el-form ref="form1">
      <el-row :gutter="5">
        <el-col :span="6">
          <el-form-item label="订单号" label-width="60px">
            <el-input v-model="orderNo" readonly type="text"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-date-picker
              v-model="orderTime"
              type="date"
              placeholder="订单日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select
              v-if="customers"
              v-model="customerId"
              placeholder="客户名称"
            >
              <el-option
                v-for="item in customers"
                :key="item.id"
                :label="item.userName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select
              v-if="orderStatusList"
              v-model="orderStatus"
              placeholder="订单状态"
            >
              <el-option
                v-for="item in orderStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="总计" label-width="50px">
            <el-input v-model="totalPrice" readonly type="text"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>    
    <br />    
    <!-- 订单明细信息录入布局 -->
    <el-row>
      <el-button type="primary" size="mini" @click="handleAdd()"
        >添加明细</el-button
      >
    </el-row>
    <el-row>
      <el-col :span="3">商品编码</el-col>
      <el-col :span="5">商品名称</el-col>
      <el-col :span="3">单价</el-col>
      <el-col :span="3">库存量</el-col>
      <el-col :span="3">购买数量</el-col>
      <el-col :span="3">小计</el-col>
      <el-col :span="4">操作</el-col>
    </el-row>    
    <el-form ref="form3" :model="orderTableData" :inline="true" size="mini">
      <el-row v-for="(item, index) in orderTableData" :key="index">
        <el-col :span="3">
          <el-form-item
            :prop="'.' + index + '.goodsCode'"
            :rules="{
              required: true,
              message: '商品编码为空',
              trigger: 'blur',
            }"
          >
            <el-input
              @click="selectGoods(index)"
              v-model="item.goodsCode"
              placeholder="商品编码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item class="el-form-item" label-width="0">
            <el-input readonly v-model="item.goodsName" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item class="el-form-item" label-width="0">
            <el-input readonly v-model="item.price" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item class="el-form-item" label-width="0">
            <el-input readonly v-model="item.num" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item
            :prop="'.' + index + '.quantity'"
            :rules="{
              required: true,
              message: '购买数量为空',
              trigger: 'blur',
            }"
            class="el-form-item"
            label-width="0"
          >
            <el-input
              @keydown.native="quantityInputLimit"
              @change="quantityChange(item, index)"
              type="number"
              v-model="item.quantity"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item class="el-form-item" label-width="0">
            <el-input
              @change="subtotalChange(item, index)"
              readonly
              v-model="item.subtotal"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <template class="el-form-item" label-width="0">
            <el-button size="mini" type="danger" @click="handleDelete(index)"
              >删除</el-button
            >
          </template>
        </el-col>
      </el-row>
      <el-row class="saveorder-btn">
        <el-button type="primary" @click="submitHandler">保存</el-button>
      </el-row>
    </el-form>
  </el-card>

  <!-- 商品选择对话框 -->
  <el-dialog title="选择商品" v-model="selectGoodsDialogVisible" width="50%">
    <el-table :data="goodsList" border stripe @row-dblclick="dataBackFillGoods">
      <el-table-column prop="id" label="商品id"></el-table-column>
      <el-table-column prop="code" label="商品编号"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="price" label="单价"></el-table-column>
      <el-table-column prop="num" label="库存量"></el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="selectGoodsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectGoodsDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
 
    const { proxy } = getCurrentInstance();    // 获取当前组件实例
    const orderNo = ref("");    // 订单号
    const orderTime = ref("");  // 订单时间
    const customerId = ref("");  // 订单客户id    
    const totalPrice = ref(0);  // 订单总金额
    const orderStatus = ref(""); // 订单状态
    // 订单明细表单引用时的名称和标识
    const form3 = ref(null);      
    const customers = ref(null); // 客户列表
    customers.value = [{}];   // 初始化客户列表
    const orderStatusList = ref(null);  // 订单状态列表
    // 初始化订单状态列表
    orderStatusList.value = [
      {
        value: "未付款",
        label: "未付款",
      },
      {
        value: "已付款",
        label: "已付款",
      },
      {
        value: "待发货",
        label: "待发货",
      },
      {
        value: "已发货",
        label: "已发货",
      },
      {
        value: "已完成",
        label: "已完成",
      },
    ]; 
    // 控制商品选择对话框是否可见
    const selectGoodsDialogVisible = ref(false);     
    const goodsList = ref(null); // 定义商品列表
    goodsList.value = [];  // 初始化商品列表
    // 单击订单明细行商品编码输入框时，当前行索引
    const currentIndex = ref(0);  
    // 订单明细数据列表
    const orderTableData = ref(null);
    // 初始化订单明细数据列表
    orderTableData.value = [];
    // 订单明细行商品编码输入框非空校验规则
    const rules = reactive({
      goodsCode: [
        { required: true, message: "请输入商品编号", trigger: "blur" },
      ],
    });

    // 向后台服务器发送get请求，获取商品列表
    const getGoodsInfoList = async () => {
      const { data: res } = await proxy.$axios.get("goods/status");
      goodsList.value = res.data;
    };

    // 向后台服务器发送get请求，获取有效客户列表
    const getValidateCustomers = async () => {
      const { data: res } = await proxy.$axios.get("customers", {
        params: {
          status: 0,
        },
      });
      customers.value = res.data;
    };

    // 向后台服务器发送get请求，通过redis获取订单编号
    const getCode = async () => {
      const { data: res } = await proxy.$axios.get("getSequence", {
        params: {
          prefix: "DD",
        },
      });
      orderNo.value = res.data;
    };

    // 处理“添加明细”按钮点击事件，添加订单明细录入空白行
    const handleAdd = () => {
      const list = {
        goodsCode: "",
        goodsName: "",
        price: "",
        num: "",
        quantity: "",
        subtotal: "",
        gid: "",
      };

      // 订单明细表单校验
      form3.value.validate((valid) => {
        if (valid) {
          orderTableData.value.push(list);
        } else {
          // 此处为验证失败代码
          proxy.$message.warning("当前行填值有误！");
        }
      });
    };

    // 处理订单明细行商品编码输入框点击事件，打开商品选择对话框
    const selectGoods = (index) => {
      selectGoodsDialogVisible.value = true;
      currentIndex.value = index;
    };

    // 保存订单
    const submitHandler = () => {
      form3.value.validate(async (valid) => {
        if (valid) {
          // 校验订单号
          if (orderNo.value === "")
            return proxy.$message.error("请开启Redis服务，生成订单号！");
          // 校验订单日期
          if (orderTime.value === "")
            return proxy.$message.error("请选择订单日期！");
          // 校验客户名称
          if (customerId.value === "")
            return proxy.$message.error("请选择客户名称！");
          // 校验订单状态
          if (orderStatus.value === "")
            return proxy.$message.error("请选择订单状态！");
          // 校验订单明细记录数
          if (orderTableData.value.length === 0)
            return proxy.$message.error("至少需要添加一条订单明细记录！");
          console.log("校验通过提交了");
          // 提交
          const { data: res } = await proxy.$axios.post("commitOrder", {
            orderNo: orderNo.value,
            ordertime: orderTime.value,
            uid: customerId.value,
            status: orderStatus.value,
            orderprice: totalPrice.value,
            orderDetails: orderTableData.value,
          });
          if (res.code != 0) return proxy.$message.error(res.msg);
          proxy.$message.success(res.msg);
          proxy.$router.push("/home");
        } else {
          proxy.$message({
            showClose: true,
            message: "请完善列表中的数据!",
            type: "warning",
          });
        }
      });
    };

    // 处理商品选择对话框中表格行的双击事件，
    // 将双击行的商品信息添加的当前订单明细行相应列
    const dataBackFillGoods = async (row, event, column) => {
      orderTableData.value[currentIndex.value].gid = row.id;
      orderTableData.value[currentIndex.value].goodsCode = row.code;
      orderTableData.value[currentIndex.value].goodsName = row.name;
      orderTableData.value[currentIndex.value].price = row.price;
      orderTableData.value[currentIndex.value].num = row.num;
      orderTableData.value[currentIndex.value].quantity = Number(1);
      orderTableData.value[currentIndex.value].subtotal = Number(row.price);
      selectGoodsDialogVisible.value = false;
      // 更新总金额
      var sum = 0;
      orderTableData.value.forEach((item) => {
        sum = Number(sum) + Number(item.subtotal);
      });
      totalPrice.value = Number(sum);
    };

    // 删除订单明细
    const handleDelete = (index) => {
      // 更新总金额
      totalPrice.value =
        totalPrice.value - Number(orderTableData.value[index].subtotal);
      orderTableData.value.splice(index, 1);
    };

    // 购买数量变化
    const quantityChange = (row, index) => {
      if (row.quantity < 1) {
        row.quantity = 1;
      }
      // 控制购买数量
      if (Number(row.quantity) > Number(row.num) || Number(row.quantity) < 1) {
        proxy.$message.warning("购买数量不能超过库存数量，且必须大于0！");
        orderTableData.value[index].quantity = "";
        orderTableData.value[index].subtotal = "";
      }

      // 更新小计
      orderTableData.value[index].subtotal = Number(
        Number(row.price) * Number(row.quantity)
      );

      // 更新总金额
      var sum = 0;
      orderTableData.value.forEach((item) => {
        sum = Number(sum) + Number(item.subtotal);
      });
      totalPrice.value = Number(sum);
    };

    // 控制购买数量，不允许输入 'E'、'e'、'.'、'-'
    const quantityInputLimit = (e) => {
      let key = e.key;
      if (
        key === "-" ||
        key === "E" ||
        key === "e" ||
        key === "." ||
        Number(key) < 1
      ) {
        e.returnValue = false;
        return false;
      }
      return true;
    };

    onMounted(() => {
      getGoodsInfoList();
      getValidateCustomers();
      getCode();
    });

    
</script>
<style lang="less" scoped>
.el-row {
  margin-bottom: 3px;
  font-size: 12px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.el-form-item {
  margin-bottom: 0px;
}
.saveorder-btn {
  margin-top: 15px;
  text-align: center;
}
</style>


